package com.sencorsta.ids.pos;

import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.opensocket.OpenMessage;
import com.sencorsta.utils.date.DateUtil;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import static java.lang.System.arraycopy;

/**
 * 回调服务器的反馈信息
 *
 * @author ICe
 */
@Sharable
public class PosSimHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Out.debug("Client异常:" + ctx.channel() + cause.getMessage());
        ctx.channel().close();
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Out.debug("Client添加:" + ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Out.debug("Client移除:" + ctx.channel());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object packet) throws Exception {
        Out.debug("");
        Out.debug("Client收到消息:" + ctx.channel() + packet);
        PosMassage msg = (PosMassage) packet;
        byte[] recv = ((PosMassage) packet).arr;
        // mypack.ans8583Fields(bt,bt.length,mypack.fieldsRecv);
        //解析
        Out.debug("开始解析...");
        ICe8583Ans myans = ctx.channel().attr(PosSim.ans).get();
        int ret = myans.ans8583QD(recv, recv.length);

        Out.debug(myans.pack.toString());
        Out.debug(myans.getFields(myans.fieldsRecv));
        Out.debug("ret:",ret);
//        if (ret == 0) {
//            byte[] send = new byte[myans.pack.txLen];
//            int money = 10; //1分
//            String time = DateUtil.getTime("HHmmss");
//            String date = DateUtil.getTime("yyMMdd");
//            myans.frame8583QRWX(money, time, date, myans.fieldsSend, myans.pack);
//            //打印出待发送的报文
//            send = new byte[myans.pack.txLen];
//            arraycopy(myans.pack.txBuffer, 0, send, 0, myans.pack.txLen);
//
//            PosMassage msg2 = new PosMassage();
//            msg2.arr = send;
//            Out.debug("发送数据开始:",ret);
//            ctx.channel().write(msg2);
//        }


//		OpenMessage msg=(OpenMessage) packet;
//		Out.debug(msg.toStringPlus());
    }

}